<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>jdk动态代理及源码解析 | 程序员小航</title><meta name="keywords" content="Spring,动态代理"><meta name="author" content="liuzhihang"><meta name="copyright" content="liuzhihang"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="Spring动态代理可以选择使用jdk动态代理, 或者cglib动态代理,  jdk动态代理位于 java.lang.reflect 包下.">
<meta property="og:type" content="article">
<meta property="og:title" content="jdk动态代理及源码解析">
<meta property="og:url" content="https://liuzhihang.com/2018/05/17/jdk-dynamic-proxy-and-source-code-analysis.html">
<meta property="og:site_name" content="程序员小航">
<meta property="og:description" content="Spring动态代理可以选择使用jdk动态代理, 或者cglib动态代理,  jdk动态代理位于 java.lang.reflect 包下.">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/bram-naus-n8Qb1ZAkK88-unsplash.jpg">
<meta property="article:published_time" content="2018-05-17T11:55:01.000Z">
<meta property="article:modified_time" content="2020-04-04T06:27:13.047Z">
<meta property="article:author" content="liuzhihang">
<meta property="article:tag" content="Spring">
<meta property="article:tag" content="动态代理">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/bram-naus-n8Qb1ZAkK88-unsplash.jpg"><link rel="shortcut icon" href="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/favicon.ico"><link rel="canonical" href="https://liuzhihang.com/2018/05/17/jdk-dynamic-proxy-and-source-code-analysis"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//www.google-analytics.com" crossorigin=""/><link rel="preconnect" href="//pingjs.qq.com"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><meta name="google_site_verification" content="GZshAnnrC-4eCrl5h-e_5Rdk4lOUhRK7ShULoRi2q0E"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><script async="async" src="https://www.googletagmanager.com/gtag/js?id=UA-126394362-1"></script><script>window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-126394362-1');
</script><script>var _mtac = {};
(function() {
    var mta = document.createElement("script");
    mta.src = "//pingjs.qq.com/h5/stats.js?v2.0.4";
    mta.setAttribute("name", "MTAH5");
    mta.setAttribute("sid", "66540676");
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(mta, s);
})();
</script><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: {"limitDay":730,"position":"top","messagePrev":"It has been","messageNext":"days since the last update, the content of the article may be outdated."},
  highlight: undefined,
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'jdk动态代理及源码解析',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2020-04-04 14:27:13'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if (GLOBAL_CONFIG_SITE.isHome && /iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="//at.alicdn.com/t/font_1608878_xsf93f0c1a.css"><meta name="generator" content="Hexo 5.2.0"><link rel="alternate" href="/atom.xml" title="程序员小航" type="application/atom+xml">
</head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/404/avatar.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">145</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">55</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">31</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-layer-group"></i><span> 导航</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/categories/"><i class="fa-fw fas fa-bookmark"></i><span> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 推荐</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/books/"><i class="fa-fw fas fa-book"></i><span> 书单</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-film"></i><span> 电影</span></a></li><li><a class="site-page child" href="/games/"><i class="fa-fw fas fa-gamepad"></i><span> 游戏</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/contact/"><i class="fa-fw fas fa-comments"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-address-book"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-user-circle"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 其他</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" target="_blank" rel="noopener" href="https://juejin.im/user/1987506650493117"><i class="fa-fw iconfont iconjuejin-1"></i><span> 掘金</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://www.zhihu.com/people/liuzhihang"><i class="fa-fw iconfont iconzhihu1"></i><span> 知乎</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://www.infoq.cn/profile/00B8AE08DA916E/publish"><i class="fa-fw iconfont iconweibiaoti-1"></i><span> InfoQ</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://blog.csdn.net/qq_36535538"><i class="fa-fw iconfont iconcsdn"></i><span> CSDN</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://leetcode-cn.com/u/liuzhihang/"><i class="fa-fw iconfont iconleetcode"></i><span> LeetCode</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/bram-naus-n8Qb1ZAkK88-unsplash.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">程序员小航</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-layer-group"></i><span> 导航</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/categories/"><i class="fa-fw fas fa-bookmark"></i><span> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 推荐</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/books/"><i class="fa-fw fas fa-book"></i><span> 书单</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-film"></i><span> 电影</span></a></li><li><a class="site-page child" href="/games/"><i class="fa-fw fas fa-gamepad"></i><span> 游戏</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/contact/"><i class="fa-fw fas fa-comments"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-address-book"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-user-circle"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 其他</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" target="_blank" rel="noopener" href="https://juejin.im/user/1987506650493117"><i class="fa-fw iconfont iconjuejin-1"></i><span> 掘金</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://www.zhihu.com/people/liuzhihang"><i class="fa-fw iconfont iconzhihu1"></i><span> 知乎</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://www.infoq.cn/profile/00B8AE08DA916E/publish"><i class="fa-fw iconfont iconweibiaoti-1"></i><span> InfoQ</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://blog.csdn.net/qq_36535538"><i class="fa-fw iconfont iconcsdn"></i><span> CSDN</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://leetcode-cn.com/u/liuzhihang/"><i class="fa-fw iconfont iconleetcode"></i><span> LeetCode</span></a></li></ul></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">jdk动态代理及源码解析</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2018-05-17T11:55:01.000Z" title="发表于 2018-05-17 19:55:01">2018-05-17</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2020-04-04T06:27:13.047Z" title="更新于 2020-04-04 14:27:13">2020-04-04</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Spring/">Spring</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">2.7k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>13分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="jdk动态代理及源码解析"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span><span class="post-meta-separator">|</span><span class="post-meta-commentcount"><i class="far fa-comments fa-fw post-meta-icon"></i><span class="post-meta-label">评论数:</span><a href="/2018/05/17/jdk-dynamic-proxy-and-source-code-analysis.html#post-comment"><span class="gitalk-comment-count"></span></a></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h3 id="介绍"><a href="#介绍" class="headerlink" title="介绍"></a>介绍</h3><p>Spring动态代理可以选择使用jdk动态代理, 或者cglib动态代理,  jdk动态代理位于 java.lang.reflect 包下.</p>
<p>使用时涉及<br>接口: java.lang.reflect.InvocationHandler<br>动态代理类: java.lang.reflect.Proxy</p>
<p>注意: JDK 动态代理是基于接口的代理, 只能对实现接口的类生成代理, 不能对类进行代理</p>
<a id="more"></a>

<h3 id="使用步骤"><a href="#使用步骤" class="headerlink" title="使用步骤"></a>使用步骤</h3><p>1.创建InvocationHandler接口的实现类, 并编写invoke方法的实现<br>2.创建被代理类的接口及实现类<br>3.使用动态代理类Proxy的静态方法生成代理类实例<br>4.使用实例调用方法</p>
<h3 id="代码演示"><a href="#代码演示" class="headerlink" title="代码演示"></a>代码演示</h3><p>按照步骤编写简易逻辑代码.</p>
<h4 id="创建InvocationHandler接口的实现类"><a href="#创建InvocationHandler接口的实现类" class="headerlink" title="创建InvocationHandler接口的实现类"></a>创建InvocationHandler接口的实现类</h4><pre><code class="java">/**
 * JDK 动态代理
 * 基于接口的代理, 只能对实现接口的类生成代理, 不能对类进行代理
 *
 * @author liuzhihang
 * @date 2018/5/17 10:36
 */
public class MyInvocationHandler implements InvocationHandler &#123;

    /**
     * 目标对象
     */
    private Object target;

    public MyInvocationHandler(Object target) &#123;
        this.target = target;
    &#125;

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable &#123;

        System.out.println(&quot;jdk 动态代理 before . . . &quot;);

        System.out.println(&quot;当前代理方法为:&quot; + method);
        Object invoke = method.invoke(target, args);

        System.out.println(&quot;jdk 动态代理 after . . . &quot;);
        return invoke;
    &#125;
&#125;</code></pre>
<h4 id="创建被代理类的接口及实现类"><a href="#创建被代理类的接口及实现类" class="headerlink" title="创建被代理类的接口及实现类"></a>创建被代理类的接口及实现类</h4><pre><code class="java">/**
 * 被代理类的接口
 * @author liuzhihang
 * @date 2018/5/17 10:47
 */
public interface Subject &#123;

    /**
     * 获取名字
     * @return
     */
    String getName();

    /**
     * 获取年龄
     * @param name
     * @return
     */
    String getAge(String name);
&#125;</code></pre>
<pre><code class="java">/**
 * 被代理类
 *
 * @author liuzhihang
 * @date 2018/5/17 10:48
 */
public class SubjectImpl implements Subject &#123;

    @Override
    public String getName() &#123;
        System.out.println(&quot;SubjectImpl的获取名字方法 . . .&quot;);
        return &quot;liuzhihang&quot;;
    &#125;

    @Override
    public String getAge(String name) &#123;

        System.out.println(name + &quot;开始获取年龄 . . .&quot;);
        return &quot;25&quot;;
    &#125;
&#125;</code></pre>
<h4 id="使用动态代理类Proxy的静态方法生成代理类实例"><a href="#使用动态代理类Proxy的静态方法生成代理类实例" class="headerlink" title="使用动态代理类Proxy的静态方法生成代理类实例"></a>使用动态代理类Proxy的静态方法生成代理类实例</h4><p>获取代理类实例有以下两种方式, 一种是通过Proxy.newProxyInstance(..)获取,  一种是通过 Proxy.getProxyClass(..) 方式获取<br>1.Proxy.newProxyInstance(..)</p>
<pre><code class="java">/**
 * 当代理类实例调用方法时, 会自动跳转到代理类关联的 handler 对象, 通过 method.invoke(target, args) 进行调用
 *
 *
 * @author liuzhihang
 * @date 2018/5/17 10:49
 */
public class ProxyMainTest &#123;

    public static void main(String[] args) &#123;

        Subject subject = new SubjectImpl();

        ClassLoader classLoader = subject.getClass().getClassLoader();
        Class&lt;?&gt;[] interfaces = subject.getClass().getInterfaces();

        MyInvocationHandler handler = new MyInvocationHandler(subject);
        // 生成代理类实例
        Subject proxyInstance = (Subject) Proxy.newProxyInstance(classLoader, interfaces, handler);

        String name = proxyInstance.getName();
        String instanceAge = proxyInstance.getAge(&quot;liuzhihang&quot;);
        System.err.println(name + &quot; &quot; + instanceAge);

    &#125;
&#125;</code></pre>
<p>2.Proxy.getProxyClass(..)</p>
<pre><code class="java">/**
 * 当代理类实例调用方法时, 会自动跳转到代理类关联的 handler 对象, 通过 method.invoke(target, args) 进行调用
 * 此方式有异常抛出
 *
 * @author liuzhihang
 * @date 2018/5/17 10:49
 */
public class ProxyMainTest &#123;

    public static void main(String[] args) &#123;
        try &#123;

        Subject subject = new SubjectImpl();

        ClassLoader classLoader = subject.getClass().getClassLoader();
        Class&lt;?&gt;[] interfaces = subject.getClass().getInterfaces();

        MyInvocationHandler handler = new MyInvocationHandler(subject);

            Class&lt;?&gt; proxyClass = Proxy.getProxyClass(classLoader, interfaces);
            Constructor&lt;?&gt; constructor = proxyClass.getConstructor(InvocationHandler.class);

            Subject subject1 = (Subject) constructor.newInstance(handler);
            String name1 = subject1.getName();
            String instanceAge1 = subject1.getAge(&quot;liuzhihang&quot;);
            System.err.println(name1 + &quot; &quot; + instanceAge1);

        &#125; catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException e) &#123;
            e.printStackTrace();
        &#125;

    &#125;

&#125;</code></pre>
<h3 id="执行结果"><a href="#执行结果" class="headerlink" title="执行结果"></a>执行结果</h3><pre><code>D:\jdk1.8\bin\java.exe . . .
liuzhihang 25
jdk 动态代理 before . . .
当前代理方法为:public abstract java.lang.String com.liuzhihang.tool.proxy.jdk.Subject.getName()
SubjectImpl的获取名字方法 . . .
jdk 动态代理 after . . .
jdk 动态代理 before . . .
当前代理方法为:public abstract java.lang.String com.liuzhihang.tool.proxy.jdk.Subject.getAge(java.lang.String)
liuzhihang开始获取年龄 . . .
jdk 动态代理 after . . .

Process finished with exit code 0</code></pre>
<p>结论: 代理实例在每次调用方法是都会通过代理类进行调用</p>
<h3 id="相关源码解析"><a href="#相关源码解析" class="headerlink" title="相关源码解析"></a>相关源码解析</h3><p>完整注释可自己查看相关源码, 源码过程应当DeBug多走走.<br>1.调用 Proxy.newProxyInstance 方法</p>
<pre><code> /**
 * 返回指定接口的代理类实例，该接口将方法调用分派给指定的调用处理程序
 */
@CallerSensitive
public static Object newProxyInstance(ClassLoader loader, Class&lt;?&gt;[] interfaces, InvocationHandler h) throws IllegalArgumentException &#123;

    // 非空校验
    Objects.requireNonNull(h);

    final Class&lt;?&gt;[] intfs = interfaces.clone();

    // 获取系统安全接口
    final SecurityManager sm = System.getSecurityManager();
    if (sm != null) &#123;
        // 校验权限
        checkProxyAccess(Reflection.getCallerClass(), loader, intfs);
    &#125;

    /*
     * 从缓存中获取代理类 或者 生成新的代理类
     */
    Class&lt;?&gt; cl = getProxyClass0(loader, intfs);

    /*
     * 通过反射获取构造函数对象并生成代理类实例
     */
    try &#123;
        if (sm != null) &#123;
            checkNewProxyPermission(Reflection.getCallerClass(), cl);
        &#125;
        // 获取构造
        final Constructor&lt;?&gt; cons = cl.getConstructor(constructorParams);
        final InvocationHandler ih = h;
        // 验证代理类的修饰符
        if (!Modifier.isPublic(cl.getModifiers())) &#123;
            // 修改访问权限
            AccessController.doPrivileged(new PrivilegedAction&lt;Void&gt;() &#123;
                public Void run() &#123;
                    // 将此对象的可访问标志设置为指定的布尔值, true表示反射对象在使用时应禁止Java语言访问检查, false表示反射对象应强制执行Java语言访问检查
                    cons.setAccessible(true);
                    return null;
                &#125;
            &#125;);
        &#125;
        //生成实例, 并将参数传入构造
        return cons.newInstance(new Object[]&#123;h&#125;);
    &#125; catch (IllegalAccessException | InstantiationException e) &#123;
        throw new InternalError(e.toString(), e);
    &#125; catch (InvocationTargetException e) &#123;
        Throwable t = e.getCause();
        if (t instanceof RuntimeException) &#123;
            throw (RuntimeException) t;
        &#125; else &#123;
            throw new InternalError(t.toString(), t);
        &#125;
    &#125; catch (NoSuchMethodException e) &#123;
        throw new InternalError(e.toString(), e);
    &#125;
&#125;
</code></pre>
<p>可以看出获取代理类是在 Class&lt;?&gt; cl = getProxyClass0(loader, intfs); 处, 继续相关逻辑<br>2.获取代理类相关逻辑</p>
<pre><code>/**
 * 生成代理类, 之前必须进行权限检查
 */
private static Class&lt;?&gt; getProxyClass0(ClassLoader loader,
                                       Class&lt;?&gt;... interfaces) &#123;
    if (interfaces.length &gt; 65535) &#123;
        throw new IllegalArgumentException(&quot;interface limit exceeded&quot;);
    &#125;

    //如果由实现给定接口的给定加载器定义的代理类存在，则它将简单地返回缓存副本; 否则，它将通过Proxy Class Factory创建代理类
    return proxyClassCache.get(loader, interfaces);
&#125;</code></pre>
<p>3.proxyClassCache.get(loader, interfaces);<br>java.lang.reflect.WeakCache#get(..) 介绍</p>
<pre><code> /**
 * 通过缓存查找值, 如果缓存中没有给定的（key，sub Key）对的条目或条目已被清除，则它总是评估&#123;Key sub Key Factory&#125;函数并可选择评估&#123;Factory value&#125;函数
 */
public V get(K key, P parameter) &#123;
    // 非空校验
    Objects.requireNonNull(parameter);
    // 判断移除队列
    expungeStaleEntries();
    // 缓存key
    Object cacheKey = CacheKey.valueOf(key, refQueue);

    // 延迟加载使用二级map
    ConcurrentMap&lt;Object, Supplier&lt;V&gt;&gt; valuesMap = map.get(cacheKey);
    if (valuesMap == null) &#123;
        ConcurrentMap&lt;Object, Supplier&lt;V&gt;&gt; oldValuesMap
                = map.putIfAbsent(cacheKey,
                valuesMap = new ConcurrentHashMap&lt;&gt;());
        if (oldValuesMap != null) &#123;
            valuesMap = oldValuesMap;
        &#125;
    &#125;

    // 创建子key 并根据key 检索supplier
    Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));
    // 根据key获取supplier
    Supplier&lt;V&gt; supplier = valuesMap.get(subKey);
    Factory factory = null;

    while (true) &#123;
        if (supplier != null) &#123;
            // supplier 可能为 Factory 或者 CacheValue&lt;V&gt; 的实例, 从缓存中获取到则直接返回
            V value = supplier.get();
            if (value != null) &#123;
                return value;
            &#125;
        &#125;

        // factory不存在则创建
        if (factory == null) &#123;
            factory = new Factory(key, parameter, subKey, valuesMap);
        &#125;

        // supplier 为null
        if (supplier == null) &#123;
            // 从valuesMap获取supplier
            supplier = valuesMap.putIfAbsent(subKey, factory);
            if (supplier == null) &#123;
                // successfully installed Factory
                supplier = factory;
            &#125;
            // else retry with winning supplier
        &#125; else &#123;
            if (valuesMap.replace(subKey, supplier, factory)) &#123;
                // successfully replaced
                // cleared CacheEntry / unsuccessful Factory
                // with our Factory
                supplier = factory;
            &#125; else &#123;
                // retry with current supplier
                supplier = valuesMap.get(subKey);
            &#125;
        &#125;
    &#125;
&#125;
</code></pre>
<p>可以发现重点在 Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter)); 获取 subKey 的过程中.<br>4.subKeyFactory.apply(key, parameter)<br>Debug发现在此处调用的是 java.lang.reflect.Proxy.ProxyClassFactory 静态内部类,<br>此处根据接口的数量生成二级缓存</p>
<pre><code class="java"> /**
 * 一个工厂函数, 用于生成, 定义并返回给定ClassLoader和接口数组的代理类
 */
private static final class ProxyClassFactory
        implements BiFunction&lt;ClassLoader, Class&lt;?&gt;[], Class&lt;?&gt;&gt;
&#123;
    // 所有代理类的前缀
    private static final String proxyClassNamePrefix = &quot;$Proxy&quot;;

    // next number to use for generation of unique proxy class names
    private static final AtomicLong nextUniqueNumber = new AtomicLong();

    @Override
    public Class&lt;?&gt; apply(ClassLoader loader, Class&lt;?&gt;[] interfaces) &#123;

        // 在IdentityHashMap中, 当且仅当两个key严格相等（key1==key2）时，IdentityHashMap才认为两个key相等
        Map&lt;Class&lt;?&gt;, Boolean&gt; interfaceSet = new IdentityHashMap&lt;&gt;(interfaces.length);
        // 循环接口数组
        for (Class&lt;?&gt; intf : interfaces) &#123;
            /*
             * 验证类加载器是否将此接口的名称解析为同一个Class对象
             */
            Class&lt;?&gt; interfaceClass = null;
            try &#123;
                // 获取接口的 class
                interfaceClass = Class.forName(intf.getName(), false, loader);
            &#125; catch (ClassNotFoundException e) &#123;
            &#125;
            if (interfaceClass != intf) &#123;
                throw new IllegalArgumentException(
                        intf + &quot; is not visible from class loader&quot;);
            &#125;
            /*
             * 验证interfaceClass是否为接口
             */
            if (!interfaceClass.isInterface()) &#123;
                throw new IllegalArgumentException(
                        interfaceClass.getName() + &quot; is not an interface&quot;);
            &#125;
            /*
             * 验证接口是否重复
             */
            if (interfaceSet.put(interfaceClass, Boolean.TRUE) != null) &#123;
                throw new IllegalArgumentException(
                        &quot;repeated interface: &quot; + interfaceClass.getName());
            &#125;
        &#125;

        String proxyPkg = null;     // package to define proxy class in
        int accessFlags = Modifier.PUBLIC | Modifier.FINAL;

        /*
         * 验证所有非公开代理接口是否在同一个包中
         */
        for (Class&lt;?&gt; intf : interfaces) &#123;
            int flags = intf.getModifiers();
            if (!Modifier.isPublic(flags)) &#123;
                accessFlags = Modifier.FINAL;
                String name = intf.getName();
                int n = name.lastIndexOf(&#39;.&#39;);
                String pkg = ((n == -1) ? &quot;&quot; : name.substring(0, n + 1));
                if (proxyPkg == null) &#123;
                    proxyPkg = pkg;
                &#125; else if (!pkg.equals(proxyPkg)) &#123;
                    throw new IllegalArgumentException(
                            &quot;non-public interfaces from different packages&quot;);
                &#125;
            &#125;
        &#125;

        if (proxyPkg == null) &#123;
            // 如果没有非公开的代理接口，使用 com.sun.proxy package
            proxyPkg = ReflectUtil.PROXY_PACKAGE + &quot;.&quot;;
        &#125;

        /*
         * 为要生成的代理类选择一个名称
         */
        long num = nextUniqueNumber.getAndIncrement();
        String proxyName = proxyPkg + proxyClassNamePrefix + num;

        /*
         * 生成代理类
         */
        byte[] proxyClassFile = ProxyGenerator.generateProxyClass(proxyName, interfaces, accessFlags);
        try &#123;
            return defineClass0(loader, proxyName,
                    proxyClassFile, 0, proxyClassFile.length);
        &#125; catch (ClassFormatError e) &#123;
            /*
             * A ClassFormatError here means that (barring bugs in the
             * proxy class generation code) there was some other
             * invalid aspect of the arguments supplied to the proxy
             * class creation (such as virtual machine limitations
             * exceeded).
             */
            throw new IllegalArgumentException(e.toString());
        &#125;
    &#125;
&#125;</code></pre>
<p>5.生辰给代理类<br>byte[] proxyClassFile = ProxyGenerator.generateProxyClass(proxyName, interfaces, accessFlags);<br>可以在测试类中添加以下内容打印出代理类:</p>
<pre><code>System.setProperty(&quot;sun.misc.ProxyGenerator.saveGeneratedFiles&quot;, &quot;true&quot;);</code></pre>
<p>代理类内容如下:</p>
<pre><code class="java">//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.sun.proxy;

import com.liuzhihang.tool.proxy.jdk.Subject;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;

public final class $Proxy0 extends Proxy implements Subject &#123;
    private static Method m1;
    private static Method m3;
    private static Method m2;
    private static Method m4;
    private static Method m0;

    public $Proxy0(InvocationHandler var1) throws  &#123;
        super(var1);
    &#125;

    public final boolean equals(Object var1) throws  &#123;
        try &#123;
            return (Boolean)super.h.invoke(this, m1, new Object[]&#123;var1&#125;);
        &#125; catch (RuntimeException | Error var3) &#123;
            throw var3;
        &#125; catch (Throwable var4) &#123;
            throw new UndeclaredThrowableException(var4);
        &#125;
    &#125;

    public final String getName() throws  &#123;
        try &#123;
            return (String)super.h.invoke(this, m3, (Object[])null);
        &#125; catch (RuntimeException | Error var2) &#123;
            throw var2;
        &#125; catch (Throwable var3) &#123;
            throw new UndeclaredThrowableException(var3);
        &#125;
    &#125;

    public final String toString() throws  &#123;
        try &#123;
            return (String)super.h.invoke(this, m2, (Object[])null);
        &#125; catch (RuntimeException | Error var2) &#123;
            throw var2;
        &#125; catch (Throwable var3) &#123;
            throw new UndeclaredThrowableException(var3);
        &#125;
    &#125;

    public final String getAge(String var1) throws  &#123;
        try &#123;
            return (String)super.h.invoke(this, m4, new Object[]&#123;var1&#125;);
        &#125; catch (RuntimeException | Error var3) &#123;
            throw var3;
        &#125; catch (Throwable var4) &#123;
            throw new UndeclaredThrowableException(var4);
        &#125;
    &#125;

    public final int hashCode() throws  &#123;
        try &#123;
            return (Integer)super.h.invoke(this, m0, (Object[])null);
        &#125; catch (RuntimeException | Error var2) &#123;
            throw var2;
        &#125; catch (Throwable var3) &#123;
            throw new UndeclaredThrowableException(var3);
        &#125;
    &#125;

    static &#123;
        try &#123;
            m1 = Class.forName(&quot;java.lang.Object&quot;).getMethod(&quot;equals&quot;, Class.forName(&quot;java.lang.Object&quot;));
            m3 = Class.forName(&quot;com.liuzhihang.tool.proxy.jdk.Subject&quot;).getMethod(&quot;getName&quot;);
            m2 = Class.forName(&quot;java.lang.Object&quot;).getMethod(&quot;toString&quot;);
            m4 = Class.forName(&quot;com.liuzhihang.tool.proxy.jdk.Subject&quot;).getMethod(&quot;getAge&quot;, Class.forName(&quot;java.lang.String&quot;));
            m0 = Class.forName(&quot;java.lang.Object&quot;).getMethod(&quot;hashCode&quot;);
        &#125; catch (NoSuchMethodException var2) &#123;
            throw new NoSuchMethodError(var2.getMessage());
        &#125; catch (ClassNotFoundException var3) &#123;
            throw new NoClassDefFoundError(var3.getMessage());
        &#125;
    &#125;
&#125;</code></pre>
<p>可以看出生成的$Proxy0类继承Proxy动态代理类并实现了Subject被代理接口, 实现所有方法<br>通过 super.h.invoke(this, m1, new Object[]{var1}) 内部调用了 InvocationHandler.invoke(…)方法, 通过反射调用代理实例的方法</p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">liuzhihang</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://liuzhihang.com/2018/05/17/jdk-dynamic-proxy-and-source-code-analysis.html">https://liuzhihang.com/2018/05/17/jdk-dynamic-proxy-and-source-code-analysis.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://liuzhihang.com" target="_blank">程序员小航</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Spring/">Spring</a><a class="post-meta__tags" href="/tags/%E5%8A%A8%E6%80%81%E4%BB%A3%E7%90%86/">动态代理</a></div><div class="post_share"><div class="social-share" data-image="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/bram-naus-n8Qb1ZAkK88-unsplash.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2018/05/18/cglib-dynamic-proxy.html"><img class="prev-cover" src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/featureimages/21_nele74.jpg" onerror="onerror=null;src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">cglib动态代理</div></div></a></div><div class="next-post pull-right"><a href="/2018/02/21/lazy-singleton-mode-thread-safe.html"><img class="next-cover" src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/featureimages/21_nele74.jpg" onerror="onerror=null;src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">懒汉单例模式线程安全</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/2018/05/18/cglib-dynamic-proxy.html" title="cglib动态代理"><img class="cover" src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/featureimages/21_nele74.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2018-05-18</div><div class="title">cglib动态代理</div></div></a></div><div><a href="/2018/01/10/interceptor.html" title="Interceptor拦截器"><img class="cover" src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/featureimages/21_nele74.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2018-01-10</div><div class="title">Interceptor拦截器</div></div></a></div><div><a href="/2018/05/21/springaop-agent-selection.html" title="SpringAop代理的选择"><img class="cover" src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/featureimages/16_tk9gnq.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2018-05-21</div><div class="title">SpringAop代理的选择</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="gitalk-container"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/404/avatar.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">liuzhihang</div><div class="author-info__description">学，然后知不足；教，然后知困。</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">145</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">55</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">分类</div><div class="length-num">31</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/liuzhihang"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/liuzhihang" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="http://mail.qq.com/cgi-bin/qm_share?t=qm_mailme&amp;email=Vjo-Iyw_Pz43ODElFicneDU5Ow" target="_blank" title="Email"><i class="fas fa-envelope-open"></i></a><a class="social-icon" href="https://weibo.com/onlyhang" target="_blank" title="Weibo"><i class="fab fa-weibo"></i></a><a class="social-icon" href="https://twitter.com/liuzhihangs" target="_blank" title="Twitter"><i class="fab fa-twitter"></i></a><a class="social-icon" href="/atom.xml" target="_blank" title="RSS"><i class="fas fa-rss"></i></a><a class="social-icon" href="https://www.infoq.cn/u/liuzhihang/publish" target="_blank" title="InfoQ"><i class="iconfont iconweibiaoti-1"></i></a><a class="social-icon" href="https://juejin.im/user/1987506650493117" target="_blank" title="掘金"><i class="iconfont iconjuejin-1"></i></a><a class="social-icon" href="https://blog.csdn.net/qq_36535538" target="_blank" title="CSDN"><i class="iconfont iconcsdn"></i></a><a class="social-icon" href="https://www.zhihu.com/people/liuzhihang" target="_blank" title="知乎"><i class="iconfont iconzhihu1"></i></a><a class="social-icon" href="https://leetcode-cn.com/u/liuzhihang" target="_blank" title="LeetCode"><i class="iconfont iconleetcode"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">🧑‍💻感谢访问本站，若喜欢请收藏 ^_^ <br> <br> <img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/wechat.jpg"> <br> 个人公众号:『 程序员小航 』</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BB%8B%E7%BB%8D"><span class="toc-number">1.</span> <span class="toc-text">介绍</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8%E6%AD%A5%E9%AA%A4"><span class="toc-number">2.</span> <span class="toc-text">使用步骤</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BB%A3%E7%A0%81%E6%BC%94%E7%A4%BA"><span class="toc-number">3.</span> <span class="toc-text">代码演示</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%88%9B%E5%BB%BAInvocationHandler%E6%8E%A5%E5%8F%A3%E7%9A%84%E5%AE%9E%E7%8E%B0%E7%B1%BB"><span class="toc-number">3.1.</span> <span class="toc-text">创建InvocationHandler接口的实现类</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%88%9B%E5%BB%BA%E8%A2%AB%E4%BB%A3%E7%90%86%E7%B1%BB%E7%9A%84%E6%8E%A5%E5%8F%A3%E5%8F%8A%E5%AE%9E%E7%8E%B0%E7%B1%BB"><span class="toc-number">3.2.</span> <span class="toc-text">创建被代理类的接口及实现类</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8%E5%8A%A8%E6%80%81%E4%BB%A3%E7%90%86%E7%B1%BBProxy%E7%9A%84%E9%9D%99%E6%80%81%E6%96%B9%E6%B3%95%E7%94%9F%E6%88%90%E4%BB%A3%E7%90%86%E7%B1%BB%E5%AE%9E%E4%BE%8B"><span class="toc-number">3.3.</span> <span class="toc-text">使用动态代理类Proxy的静态方法生成代理类实例</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%89%A7%E8%A1%8C%E7%BB%93%E6%9E%9C"><span class="toc-number">4.</span> <span class="toc-text">执行结果</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%9B%B8%E5%85%B3%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%90"><span class="toc-number">5.</span> <span class="toc-text">相关源码解析</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2021/09/04/the_converter_converts_front_end_parameters_to_enumerations.html" title="使用 SpringBoot 转换器将前端参数转换为枚举"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/uztio4-T5n5Wm.jpg" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="使用 SpringBoot 转换器将前端参数转换为枚举"/></a><div class="content"><a class="title" href="/2021/09/04/the_converter_converts_front_end_parameters_to_enumerations.html" title="使用 SpringBoot 转换器将前端参数转换为枚举">使用 SpringBoot 转换器将前端参数转换为枚举</a><time datetime="2021-09-03T23:00:00.000Z" title="发表于 2021-09-04 07:00:00">2021-09-04</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/08/22/guide_to_mapper_overloading_crater_in_mybatis_plus.html" title="MyBatis-Plus 中 Mapper 重载踩坑指南"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/ze1d2z-wXDWp0.jpg" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="MyBatis-Plus 中 Mapper 重载踩坑指南"/></a><div class="content"><a class="title" href="/2021/08/22/guide_to_mapper_overloading_crater_in_mybatis_plus.html" title="MyBatis-Plus 中 Mapper 重载踩坑指南">MyBatis-Plus 中 Mapper 重载踩坑指南</a><time datetime="2021-08-21T23:00:00.000Z" title="发表于 2021-08-22 07:00:00">2021-08-22</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/07/25/tips_for_locking_and_optimizing_concurrent_scenes.html" title="并发场景加锁优化小技巧"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/MODJ8j-9ObHeB.jpg" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="并发场景加锁优化小技巧"/></a><div class="content"><a class="title" href="/2021/07/25/tips_for_locking_and_optimizing_concurrent_scenes.html" title="并发场景加锁优化小技巧">并发场景加锁优化小技巧</a><time datetime="2021-07-24T23:00:00.000Z" title="发表于 2021-07-25 07:00:00">2021-07-25</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/07/16/curator-5.html" title="ZooKeeper 分布式锁 Curator 源码 05：分布式读写锁和联锁"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/EO0tci-8Ju4bN.png" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="ZooKeeper 分布式锁 Curator 源码 05：分布式读写锁和联锁"/></a><div class="content"><a class="title" href="/2021/07/16/curator-5.html" title="ZooKeeper 分布式锁 Curator 源码 05：分布式读写锁和联锁">ZooKeeper 分布式锁 Curator 源码 05：分布式读写锁和联锁</a><time datetime="2021-07-16T13:30:30.000Z" title="发表于 2021-07-16 21:30:30">2021-07-16</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/07/15/curator-4.html" title="ZooKeeper 分布式锁 Curator 源码 04：分布式信号量和互斥锁"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/EO0tci-8Ju4bN.png" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="ZooKeeper 分布式锁 Curator 源码 04：分布式信号量和互斥锁"/></a><div class="content"><a class="title" href="/2021/07/15/curator-4.html" title="ZooKeeper 分布式锁 Curator 源码 04：分布式信号量和互斥锁">ZooKeeper 分布式锁 Curator 源码 04：分布式信号量和互斥锁</a><time datetime="2021-07-15T13:30:30.000Z" title="发表于 2021-07-15 21:30:30">2021-07-15</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2017 - 2021 By liuzhihang</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text"><a target="_blank" rel="noopener" href="http://www.beian.miit.gov.cn/"><img class="icp-icon" src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="/resources/image/icp.png"><span>备案号：京ICP备20000888号</span></a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="/js/search/local-search.js"></script><div class="js-pjax"><script>if (document.getElementsByClassName('mermaid').length) {
  if (window.mermaidJsLoad) mermaid.init()
  else {
    getScript('https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js').then(() => {
      window.mermaidJsLoad = true
      mermaid.initialize({
        theme: 'default',
      })
      false && mermaid.init()
    })
  }
}</script><script>function addGitalkSource () {
  const ele = document.createElement('link')
  ele.rel = 'stylesheet'
  ele.href= 'https://cdn.jsdelivr.net/npm/gitalk/dist/gitalk.min.css'
  document.getElementsByTagName('head')[0].appendChild(ele)
}

function loadGitalk () {
  function initGitalk () {
    var gitalk = new Gitalk(Object.assign({
      clientID: 'e48f300349e2ac2d03bd',
      clientSecret: '001c669e6269dfd9d7d9fef029cc71fd00ea69e3',
      repo: 'comments',
      owner: 'liuzhihang',
      admin: ['liuzhihang'],
      id: '23747b18a51a46886741e6a6066b5172',
      language: 'en',
      perPage: 10,
      distractionFreeMode: false,
      pagerDirection: 'last',
      createIssueManually: false,
      updateCountCallback: commentCount
    },null))

    gitalk.render('gitalk-container')
  }

  if (typeof Gitalk === 'function') initGitalk()
  else {
    addGitalkSource()
    getScript('https://cdn.jsdelivr.net/npm/gitalk@latest/dist/gitalk.min.js').then(initGitalk)
  }
}

function commentCount(n){
  let isCommentCount = document.querySelector('#post-meta .gitalk-comment-count')
  if (isCommentCount) {
    isCommentCount.innerHTML= n
  }
}

if ('Gitalk' === 'Gitalk' || !false) {
  if (false) btf.loadComment(document.getElementById('gitalk-container'), loadGitalk)
  else loadGitalk()
} else {
  function loadOtherComment () {
    loadGitalk()
  }
}</script></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>